package cc.linker.steplink.crm.merchant.service;

import cc.linker.steplink.crm.commons.utils.NumberUtils;
import cc.linker.steplink.crm.commons.utils.TransactionOrderUtil;
import cc.linker.steplink.crm.merchant.dao.AssetCenterMapper;
import cc.linker.steplink.crm.merchant.pojo.*;
import cc.linker.steplink.crm.response.GlobalException;
import cc.linker.steplink.crm.response.ResponseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AssetCenterService {
    
    private WxappletInfoPo wxappletInfoPo;
    private TblCloudtbBroadcasting broadcast;

    @Autowired
    private AssetCenterMapper assetCenterMapper;

    public AssetCenterOverViewPo getAssetCenterOverView(HttpServletRequest resRequest) {
        Map<String,Object> params =new HashMap<>();
        params.put("wxappletId",wxappletInfoPo.getWxappletId());
        if(broadcast!=null){        	
        	params.put("broadcastId",broadcast.getId());
        }
        AssetCenterOverViewPo po=assetCenterMapper.getAssetCenterOverView(params);
        //分转元
        DecimalFormat df = new DecimalFormat("#.00");
        po.setBalance(Double.valueOf(df.format((double) (po.getBalanceCent()-po.getFreezingBalanceCent())/100)));
        po.setIncome(Double.valueOf(df.format((double) po.getIncomeCent()/100)));
        po.setExpenditure(Double.valueOf(df.format((double) po.getExpenditureCent()/100)));
        po.setFreezingBalance(Double.valueOf(df.format((double) po.getFreezingBalanceCent()/100)));
        if(broadcast!=null){       	
        	po.setBroadcastId(broadcast.getId());
        	po.setBroadcastName(broadcast.getSbroadcastingName());
        }
        po.setWxappletId(Long.valueOf(wxappletInfoPo.getWxappletId()));
        po.setWxappletName(wxappletInfoPo.getWxappletName());
        return po;
    }

    public RechargeReceivablePo recharge(Double rechargeNum, HttpServletRequest resRequest) {
        //判断当前登录用户，是否有频道信息
        TblCloudtbBroadcasting broadcast = new TblCloudtbBroadcasting();
        String wxappletId=wxappletInfoPo.getWxappletId();
        Map<String, Object> params = new HashMap<>();
        params.put("wxappletId",wxappletId);
        if(broadcast!=null){
            params.put("broadcastId",broadcast.getId());
        }
        DecimalFormat df = new DecimalFormat("#.00");
        AssetCenterOverViewPo assetCenterOverViewPo=assetCenterMapper.getAssetCenterOverView(params);
        //元转分
        Long rechargeAmount = Long.valueOf(new DecimalFormat("0").format(rechargeNum*100));
        UserAccountPo account=assetCenterMapper.getMiniProgramAccount(params);
        RechargeRecordPo rechargeRecordPo = new RechargeRecordPo();
        if(broadcast!=null){       	
        	rechargeRecordPo.setBroadcastId(broadcast.getId());
        }
        rechargeRecordPo.setWxappletId(Long.valueOf(wxappletId));
        rechargeRecordPo.setRechargeAmountCent(rechargeAmount);
        rechargeRecordPo.setRechargeAccount(account.getAccountId());
        rechargeRecordPo.setRechargeState(3);//待支付
        rechargeRecordPo.setRechargeAdminId(null);
        rechargeRecordPo.setRechargeOrder(TransactionOrderUtil.TYPE_RECHARGE+ TransactionOrderUtil.getPrimaryKey());
        assetCenterMapper.saveRechargeRecord(rechargeRecordPo);
        RechargeReceivablePo receivablePo = new RechargeReceivablePo();
        receivablePo.setRechargeId(rechargeRecordPo.getRechargeId());
        receivablePo.setRechargeNum(rechargeNum);
        receivablePo.setBalance(Double.valueOf(df.format(((double)assetCenterOverViewPo.getBalanceCent()-(double)assetCenterOverViewPo.getFreezingBalanceCent())/100)));
        receivablePo.setWxappletName(wxappletInfoPo.getWxappletName());
        receivablePo.setReceivableAccount("3333222222222");
        receivablePo.setReceivableAddress("招商银行股份有限公司杭州高薪支行");
        receivablePo.setReceivableName("杭州联汇");
        return receivablePo;
    }

    public void rechargeVoucher(Map<String, Object> params) {
        assetCenterMapper.saveRechargeVoucher(params);
        assetCenterMapper.updateRechargeType(params);
    }

    public BaseDto saveBankCard(BankCardPo bankCardPo, HttpServletRequest resRequest) {
        BaseDto dto = new BaseDto();
        String wxappletId=(String)resRequest.getSession().getAttribute("wxappletId");
        Map<String,Object> params =new HashMap<>();
        params.put("wxappletId",wxappletId);
        bankCardPo.setWxappletId(Long.valueOf(wxappletId));
        if(broadcast!=null){
            params.put("broadcastId",broadcast.getId());
            bankCardPo.setBroadcastId(broadcast.getId());
        }
        if(bankCardPo.getBankCardId()!=null){
            assetCenterMapper.updateBankCard(bankCardPo);
        }else{
            /*Integer count=assetCenterMapper.getBankCardNum(params);
            if(count<3){*/
                assetCenterMapper.addBankCard(bankCardPo);
            /*}else{
                dto.setRt(0);
                dto.setDes("最多只能添加3张银行卡信息");
            }*/
        }
        return dto;
    }

    public List<BankCardPo> getBankCardList(HttpServletRequest resRequest) {
        String wxappletId=(String)resRequest.getSession().getAttribute("wxappletId");
        Map<String,Object> params =new HashMap<>();
        params.put("wxappletId",wxappletId);
        if(broadcast!=null){
            params.put("broadcastId",broadcast.getId());
        }
        List<BankCardPo> bankCardPos=assetCenterMapper.getBankCardList(params);
        return bankCardPos;
    }

    public void delBankCard(Long bankCardId, HttpServletRequest resRequest) {
        String wxappletId=(String)resRequest.getSession().getAttribute("wxappletId");
        Map<String,Object> params =new HashMap<>();
        params.put("bankCardId",bankCardId);
        params.put("wxappletId",wxappletId);
        if(broadcast!=null){
            params.put("broadcastId",broadcast.getId());
        }
        assetCenterMapper.delBankCard(params);
    }

    public BasePageDto<WithdrawInfoPo> getWithdrawList(Map<String, Object> params, HttpServletRequest resRequest) {
        BasePageDto<WithdrawInfoPo> dto = new BasePageDto<WithdrawInfoPo>();
        String wxappletId=(String)resRequest.getSession().getAttribute("wxappletId");
        params.put("wxappletId",wxappletId);
        if(broadcast!=null){
            params.put("broadcastId",broadcast.getId());
        }
        Integer perPage = (Integer) params.get("perPage");
        Integer pageIndex = (Integer) params.get("pageIndex");
        Integer start=pageIndex*perPage;
        params.put("start",start);
        Integer total=assetCenterMapper.getWithdrawCount(params);
        List<WithdrawInfoPo> withdrawInfoPos=assetCenterMapper.getWithdrawList(params);
        DecimalFormat df = new DecimalFormat("#.00");
        for(WithdrawInfoPo po:withdrawInfoPos){
            //分转元
            double s = ((double) po.getWithdrawValueCent()/100);
            po.setWithdrawValue(Double.valueOf(df.format(s)));
        }
        dto.setCon(withdrawInfoPos);
        dto.setCurrentPage(pageIndex);
        dto.setCount(total);
        dto.setPerPage((Integer)params.get("perPage"));
        dto.setTotalPage((total%perPage==0)?(total/perPage):(total/perPage+1));
        return dto;
    }

    public BasePageDto<WithdrawInfoPo> getSmpWithdrawList(Map<String, Object> params, HttpServletRequest resRequest) {
        BasePageDto<WithdrawInfoPo> dto = new BasePageDto<WithdrawInfoPo>();
        Integer perPage = (Integer) params.get("perPage");
        Integer pageIndex = (Integer) params.get("pageIndex");
        Integer start=pageIndex*perPage;
        params.put("start",start);
        Integer total=assetCenterMapper.getWithdrawCount(params);
        List<WithdrawInfoPo> withdrawInfoPos=assetCenterMapper.getWithdrawList(params);
        DecimalFormat df = new DecimalFormat("#.00");
        for(WithdrawInfoPo po:withdrawInfoPos){
            //分转元
            double s = ((double) po.getWithdrawValueCent()/100);
            po.setWithdrawValue(Double.valueOf(df.format(s)));
        }
        dto.setCon(withdrawInfoPos);
        dto.setCurrentPage(pageIndex);
        dto.setCount(total);
        dto.setPerPage((Integer)params.get("perPage"));
        dto.setTotalPage((total%perPage==0)?(total/perPage):(total/perPage+1));
        return dto;
    }

    public BaseDto saveWithdraw(WithdrawInfoPo withdrawInfoPo, HttpServletRequest resRequest) {
        BaseDto dto=new BaseDto();
        String wxappletId=(String)resRequest.getSession().getAttribute("wxappletId");
        Map<String,Object> params =new HashMap<>();
        params.put("wxappletId",wxappletId);
        if(broadcast!=null){
            params.put("broadcastId",broadcast.getId());
        }
        //元转分
        Long withdrawValue = Long.valueOf(new DecimalFormat("0").format(withdrawInfoPo.getWithdrawValue()*100));
        withdrawInfoPo.setWithdrawValueCent(withdrawValue);
        //params.put("operate",1);//操作类型  1 为不扣钱
        UserAccountPo account=assetCenterMapper.getMiniProgramAccount(params);
        AssetCenterOverViewPo po=assetCenterMapper.getAssetCenterOverView(params);
        if((po.getBalanceCent()-po.getFreezingBalanceCent())>=withdrawValue){
            withdrawInfoPo.setWithdrawAccount(account.getAccountId());
            withdrawInfoPo.setWxappletId(Long.valueOf(wxappletId));
            if(broadcast!=null){
                withdrawInfoPo.setBroadcastId(broadcast.getId());
            }
            withdrawInfoPo.setOperateUserId(null);
            withdrawInfoPo.setWithdrawOrder(TransactionOrderUtil.TYPE_WITHDRAW+TransactionOrderUtil.getPrimaryKey());
            assetCenterMapper.saveWithdraw(withdrawInfoPo);
            params.put("withdrawRecordId",withdrawInfoPo.getWithdrawRecordId());
            //assetCenterMapper.updateWithdrawAccountInfo(params);
        }else{
            dto.setRt(0);
            dto.setDes("账户余额不足！");
        }
        return dto;
    }

    public BasePageDto<RechargeRecordPo> getRechargeList(Map<String, Object> params, HttpServletRequest resRequest) {
        DecimalFormat df = new DecimalFormat("#.00");
        BasePageDto<RechargeRecordPo> dto = new BasePageDto<RechargeRecordPo>();
        String wxappletId=(String)resRequest.getSession().getAttribute("wxappletId");
        params.put("wxappletId",wxappletId);
        if(broadcast!=null){
            params.put("broadcastId",broadcast.getId());
        }
        Integer perPage = (Integer) params.get("perPage");
        Integer pageIndex = (Integer) params.get("pageIndex");
        Integer start=pageIndex*perPage;
        params.put("start",start);
        Integer total=assetCenterMapper.getRechargeCount(params);
        List<RechargeRecordPo> rechargeList=assetCenterMapper.getRechargeList(params);
        for(RechargeRecordPo po:rechargeList){
            //分转元
            double s = ((double) po.getRechargeAmountCent()/100);
            po.setRechargeAmount(Double.valueOf(df.format(s)));
        }
        dto.setCon(rechargeList);
        dto.setCurrentPage(pageIndex);
        dto.setCount(total);
        dto.setPerPage(perPage);
        dto.setTotalPage((total%perPage==0)?(total/perPage):(total/perPage+1));
        return dto;
    }

    public BasePageDto<RechargeRecordPo> getSmpRechargeList(Map<String, Object> params, HttpServletRequest resRequest) {
        BasePageDto<RechargeRecordPo> dto = new BasePageDto<RechargeRecordPo>();
        Integer perPage = (Integer) params.get("perPage");
        Integer pageIndex = (Integer) params.get("pageIndex");
        Integer start=pageIndex*perPage;
        params.put("start",start);
        Integer total=assetCenterMapper.getRechargeCount(params);
        List<RechargeRecordPo> rechargeList=assetCenterMapper.getRechargeList(params);
        DecimalFormat df = new DecimalFormat("#.00");
        for(RechargeRecordPo po:rechargeList){
            //分转元
            double s = ((double) po.getRechargeAmountCent()/100);
            po.setRechargeAmount(Double.valueOf(df.format(s)));
        }
        dto.setCon(rechargeList);
        dto.setCurrentPage(pageIndex);
        dto.setCount(total);
        dto.setPerPage(perPage);
        dto.setTotalPage((total%perPage==0)?(total/perPage):(total/perPage+1));
        return dto;
    }

    public void rechargeReview(Map<String, Object> params, HttpServletRequest resRequest) {
        Integer rechargeState = (Integer) params.get("rechargeState");
        assetCenterMapper.rechargeReview(params);
        if(rechargeState==1){//审核通过时
            assetCenterMapper.updateRechargeAccountInfo(params);
            assetCenterMapper.insertRechargeTradeRecord(params);
        }
    }

    public void withdrawReview(Map<String, Object> params, HttpServletRequest resRequest) {
        Integer withdrawState = (Integer) params.get("withdrawState");
        assetCenterMapper.withdrawReview(params);
        params.put("operate",-1);//操作类型  1为扣钱
        if(withdrawState==1){//审核通过时
            assetCenterMapper.updateWithdrawAccountInfo(params);
            assetCenterMapper.insertWithdrawTradeRecord(params);
        }
    }

    public List<TransactionDetailsPo> getTransactionDetails(Map<String, Object> params) {
        String salerId = (String) params.get("salerId");
        List<TransactionDetailsPo> transactionDetails = assetCenterMapper.getTransactionDetailsNew(params);
        for(TransactionDetailsPo po:transactionDetails){
            if (!StringUtils.isEmpty(salerId)) {// 小b
                // 大B交易类型 1:活动营销  2:提现   3:充值  4:订单入账
                Integer tradeType = po.getTradeType();
                if (tradeType == 1) {// 活动营销
                    // 活动营销下的1.订单收益2.商品服务费3.开通麦服务费4.开通麦平台收入5.商品推广费6.开通麦推广费7.开通高推平台收入8.开通高推服务费
                    Integer tradeSubType = po.getTradeSubType();
                    if (tradeSubType != null) {
                        // 1归为订单入账11  2、4、5归为营销返润12
                        switch (tradeSubType){
                            case 1: po.setTradeType(11); break;
                            case 2: po.setTradeType(12); break;
                            case 4: po.setTradeType(12); break;
                            case 5: po.setTradeType(12); break;
                            default: po.setTradeType(0);
                        }
                    }
                }
            }
            //分转元
            if(po.getAccountBalanceCent()!=null){
                double accountBalance = ((double) po.getAccountBalanceCent()/100);
                po.setAccountBalance(accountBalance);
            }
            if(po.getTradeSumCent()!=null){
                double tradeSum = ((double) po.getTradeSumCent()/100);
                po.setTradeSum(tradeSum);
            }
        }
        return transactionDetails;
    }
    
    public List<AccountSummaryPo> getAccountSummary(Map<String, Object> params)
            throws GlobalException {
        List<AccountSummaryPo> accountSummaryPoList;
        String scale = (String) params.get("scale");
        String salerId = (String) params.get("salerId");
        if (StringUtils.isEmpty(salerId)) {// 非小b
            if ("month".equals(scale)) {// 按月搜索，按日展示
                accountSummaryPoList=assetCenterMapper.getAccountSummaryByDay(params);
            } else if ("year".equals(scale)) {// 按年搜索，按月展示
                accountSummaryPoList=assetCenterMapper.getAccountSummaryByMonth(params);
            } else {
                throw new GlobalException(new ResponseException(400, "格式非法"));
            }
        } else {// 小b
            if ("month".equals(scale)) {
                accountSummaryPoList=assetCenterMapper.getAccountSummarySalerByDay(params);
            } else if ("year".equals(scale)) {
                accountSummaryPoList=assetCenterMapper.getAccountSummarySalerByMonth(params);
            } else {
                throw new GlobalException(new ResponseException(400, "格式非法"));
            }
        }
        

        accountSummaryPoList.forEach(po -> {
            //分转元
            po.setPaySummary(NumberUtils.fenToYuan(po.getPaySummaryCent()));
            po.setIncomeSummary(NumberUtils.fenToYuan(po.getIncomeSummaryCent()));
            po.setBalance(NumberUtils.fenToYuan(po.getBalanceCent()));
        }
        );
        return accountSummaryPoList;
    }
    
    public void setDefaultBankCard(Long bankCardId, Integer isDefault, HttpServletRequest resRequest) {
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("bankCardId",bankCardId);
        params.put("isDefault",isDefault);
        String wxappletId=(String)resRequest.getSession().getAttribute("wxappletId");
        params.put("wxappletId",wxappletId);
        if(broadcast!=null){
            params.put("broadcastId",broadcast.getId());
        }
        assetCenterMapper.setBankCardUndefault(params);
        if(isDefault==1){//设为默认
            assetCenterMapper.setDefaultBankCard(params);
        }
    }
}
